package com.dianxun.exam.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

/**
 * 更新信息实体类 UpdateInfo.java @ 2012-8-11
 * <p>
 * 更新xml文件格式 文件名 update.xml 存成utf-8 <info> <version>版本</version> <url>下载网址</url>
 * <description>更新说明</description> <filename>下载文件名</filename> </info>
 * <p>
 * 更新调用 CheckVersion()
 * <p>
 * 当前版本信息调用 getVersionName()
 */
public class UpdateInfo {
    // 更新xml地址
    private static final String UpdateXmlUrl = "http://192.168.1.100/exam/update.xml";
    private static final String TAG = "UpdateInfo";
    private static UpdateInfo updateInfo = null;
    private String version; // 版本号
    private String url; // 新版本存放url路径
    private String fileName;
    private String description; // 更新说明信息，比如新增什么功能特性等
    private String enable; // 更新说明信息，比如新增什么功能特性等
    private static String savefolder = "/sdcard/DownLoad";
    //服务器地址
    private String serverAddress;

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getEnable() {
        return enable;
    }

    public void setEnable(String enable) {
        this.enable = enable;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    /**
     * 获取版本号
     *
     * @param context 上下文
     * @return
     * @throws NameNotFoundException
     */

    public static String getVersionName(Context context) {

        // 获取PackageManager 实例
        PackageManager packageManager = context.getPackageManager();

        String ver = "";
        // 获得context所属类的包名，0表示获取版本信息
        PackageInfo packageInfo;
        try {
            packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);

            ver = packageInfo.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

        return ver;
    }


    /**
     * 检查是否需要更新程序
     */
    public static void CheckVersion(final Activity context) {
        URL url;
        List<UpdateInfo> list = null;
        try {
            url = new URL(UpdateXmlUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(1000);
            list = XmlUtil.xmlParseList(connection.getInputStream());
        } catch (MalformedURLException e) {
            Log.e(TAG, e.toString());
        } catch (IOException e) {
            Log.e(TAG, e.toString());
        }
        // 连接失败
        if (list == null || list.isEmpty()) {
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context, "未获取到版本更新信息!", Toast.LENGTH_SHORT).show();
                }
            });
            return;
        }
        for (UpdateInfo info : list) {
            if ("1".equals(info.getEnable())) {
                updateInfo = info;
                break;
            }
        }
        if (updateInfo == null) {
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context, "未获取到版本更新信息!", Toast.LENGTH_SHORT).show();
                }
            });
            return;
        }
        // 版本相同
        if (getVersionName(context).equals(updateInfo.getVersion())) {
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context, "已是最新版本!", Toast.LENGTH_SHORT).show();
                }
            });
            return;
            // Toast.makeText(this, "版本相同,不需要升级!", Toast.LENGTH_SHORT).show();
        }
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showUpdateDialog(context);
            }
        });

    }


    public static void showUpdateDialog(final Context context) {

        AlertDialog alertDialog = new AlertDialog.Builder(context)
                .setTitle("提示检测到新版本,确定升级吗?")
                // .setIcon(R.drawable.ask)
                .setMessage(updateInfo.getDescription()).setPositiveButton("确定",

                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                Intent intent = new Intent();
                                Uri uri = Uri.parse(updateInfo.getUrl());
                                intent.setAction(Intent.ACTION_VIEW);
                                intent.setData(uri);
                                context.startActivity(intent);
                            }
                        })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                }).create();
        alertDialog.show();
    }


}
